<template>
  <div class="panel-tab__content">
    <!--    <el-upload-->
    <!--      class="upload-demo"-->
    <!--      :show-file-list=false-->
    <!--      :action="uploadUrl"-->
    <!--      multiple-->
    <!--      :on-success="handleAvatarSuccess"-->
    <!--      v-if="this.$route.params.type === 1 || this.$route.params.type == '1'"-->
    <!--    >-->
    <!--      <el-button size="small" icon="el-icon-upload">点击上传</el-button>-->
    <!--    </el-upload>-->
    <el-button size="small" @click="isDialog" v-if="this.$route.params.type === 1 || this.$route.params.type == '1'">
      点击选择
    </el-button>
    <!--字段列表-->
    <div class="element-property list-property">
      <el-table :data="fileTable" size="mini" max-height="240" border fit>
        <el-table-column label="制度编号" align="center" key="systemCode" prop="systemCode"/>
        <el-table-column label="操作" width="90px"
                         v-if="this.$route.params.type === 1 || this.$route.params.type === '1'"
        >
          <template slot-scope="{ row, $index }">
            <el-button size="mini" type="text" style="color: #448EF7" @click="getInfo(row)">详情
            </el-button>
            <el-button size="mini" type="text" style="color: #448EF7" @click="(row, $index)">移除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-dialog title="制度文件选择" :visible.sync="institutionOpen" append-to-body width="90%">
      <choose-institution-table @checkData="checkData" ref="chooseInstitutionTable"></choose-institution-table>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="deptSubmitForm">确 定</el-button>
        <el-button size="small" @click="deptCancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="制度文件详情" :visible.sync="institutionInfoOpen" append-to-body width="70%">
      <el-form ref="info" :model="info" label-width="120px">
        <h4 style="border-left:5px solid #0089ff;padding: 5px;">基本信息</h4>
        <el-row>
          <el-col :span="12">
            <el-form-item label="制度名称:" prop="activityId">
              {{ info.systemNumber }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="制度编号:" prop="event">
              {{ info.systemCode }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="制度文号:" prop="description">
              {{ info.systemNo }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="编制部门:" prop="regulations">
              {{ info.superintendent }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="签发日期:" prop="prohibitedMatter">
              {{ info.issueDate }}
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="institutionInfoOpen= false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import ChooseInstitutionTable from '@/plugins/package/tree/chooseInstitutionTable'
import { getRisk } from '@/api/lc/risk'

export default {
  name: 'ElementForm',
  components: {
    ChooseInstitutionTable
  },
  props: {
    id: String,
    businessObject: Object,
    type: String,
    idEditDisabled: {
      type: Boolean,
      default: true
    }
  },
  inject: {
    prefix: 'prefix',
    width: 'width'
  },
  data() {
    return {
      info: {},
      institutionInfoOpen: false,
      institutionOpen: false,
      downLoadUrl: 'http://127.0.0.1:8089/file/',
      uploadUrl: process.env.VUE_APP_UPLOAD_URL,
      formOptions: [],
      fileList: [],
      fileTable: [],
      formKey: '',
      localScope: true,
      businessKey: '',
      optionModelTitle: '',
      fieldList: [],
      formFieldForm: {},
      fieldType: {
        long: '长整型',
        string: '字符串',
        boolean: '布尔类',
        date: '日期类',
        enum: '枚举类',
        custom: '自定义类型'
      },
      formFieldIndex: -1, // 编辑中的字段， -1 为新增
      formFieldOptionIndex: -1, // 编辑中的字段配置项， -1 为新增
      fieldModelVisible: false,
      fieldOptionModelVisible: false,
      fieldOptionForm: {}, // 当前激活的字段配置项数据
      fieldOptionType: '', // 当前激活的字段配置项弹窗 类型
      fieldEnumList: [], // 枚举值列表
      fieldConstraintsList: [], // 约束条件列表
      fieldPropertiesList: [], // 绑定属性列表
      otherExtensionList: [],
      multipleSelection: []
    }
  },
  watch: {
    businessObject: {
      immediate: true,
      handler: function(val) {
        if (val) {
          this.$nextTick(() => this.resetFormList())
        }
      }
    }
  },
  created() {
  },
  methods: {
    infoHandle(){

    },
    resetFormList() {
      console.log('刷新')
      this.fileTable = []
      this.bpmnElement = window?.bpmnInstances?.bpmnElement
      this.elementBaseInfo = JSON.parse(JSON.stringify(this.bpmnElement.businessObject))

      this.bpmnElementProperties =
        this.bpmnElement.businessObject?.extensionElements?.values?.filter(ex => {
          if (ex.$type !== `${this.prefix}:Properties`) {
            this.otherExtensionList.push(ex)
          }
          return ex.$type === `${this.prefix}:Properties`
        }) ?? []
      // 保存所有的 扩展属性字段
      this.bpmnElementPropertyList = this.bpmnElementProperties.reduce((pre, current) => pre.concat(current.values), [])
      this.elementPropertyList = JSON.parse(JSON.stringify(this.bpmnElementPropertyList ?? []))
      let systemFileValue = ''
      for (let i = 0; i < this.elementPropertyList.length; i++) {
        let key = this.elementPropertyList[i].name
        console.log(key, this.elementPropertyList[i])
        if (key === 'systemFile') {
          this.fileTable = JSON.parse(this.elementPropertyList[i].value)
        }
      }
    },
    updateElementFormKey() {
      window.bpmnInstances.modeling.updateProperties(this.bpmnELement, { formKey: this.formKey })
    },
    updateElementFormScope() {
      window.bpmnInstances.modeling.updateProperties(this.bpmnELement, { localScope: this.localScope })
    },
    updateElementBusinessKey() {
      window.bpmnInstances.modeling.updateModdleProperties(this.bpmnELement, this.formData, { businessKey: this.businessKey })
    },
    // 根据类型调整字段type
    changeFieldTypeType(type) {
      this.$set(this.formFieldForm, 'type', type === 'custom' ? '' : type)
    },
    // 打开字段详情侧边栏
    openFieldForm(field, index) {
      this.formFieldIndex = index
      if (index !== -1) {
        const FieldObject = this.formData.fields[index]
        this.formFieldForm = JSON.parse(JSON.stringify(field))
        // 设置自定义类型
        this.$set(this.formFieldForm, 'typeType', !this.fieldType[field.type] ? 'custom' : field.type)
        // 初始化枚举值列表
        field.type === 'enum' && (this.fieldEnumList = JSON.parse(JSON.stringify(FieldObject?.values || [])))
        // 初始化约束条件列表
        this.fieldConstraintsList = JSON.parse(JSON.stringify(FieldObject?.validation?.constraints || []))
        // 初始化自定义属性列表
        this.fieldPropertiesList = JSON.parse(JSON.stringify(FieldObject?.properties?.values || []))
      } else {
        this.formFieldForm = {}
        // 初始化枚举值列表
        this.fieldEnumList = []
        // 初始化约束条件列表
        this.fieldConstraintsList = []
        // 初始化自定义属性列表
        this.fieldPropertiesList = []
      }
      this.fieldModelVisible = true
    },
    // 打开字段 某个 配置项 弹窗
    openFieldOptionForm(option, index, type) {
      this.fieldOptionModelVisible = true
      this.fieldOptionType = type
      this.formFieldOptionIndex = index
      if (type === 'property') {
        this.fieldOptionForm = option ? JSON.parse(JSON.stringify(option)) : {}
        return (this.optionModelTitle = '属性配置')
      }
      if (type === 'enum') {
        this.fieldOptionForm = option ? JSON.parse(JSON.stringify(option)) : {}
        return (this.optionModelTitle = '枚举值配置')
      }
      this.fieldOptionForm = option ? JSON.parse(JSON.stringify(option)) : {}
      return (this.optionModelTitle = '约束条件配置')
    },
    // 保存字段 某个 配置项
    saveFieldOption() {
      if (this.formFieldOptionIndex === -1) {
        if (this.fieldOptionType === 'property') {
          this.fieldPropertiesList.push(this.fieldOptionForm)
        }
        if (this.fieldOptionType === 'constraint') {
          this.fieldConstraintsList.push(this.fieldOptionForm)
        }
        if (this.fieldOptionType === 'enum') {
          this.fieldEnumList.push(this.fieldOptionForm)
        }
      } else {
        this.fieldOptionType === 'property' && this.fieldPropertiesList.splice(this.formFieldOptionIndex, 1, this.fieldOptionForm)
        this.fieldOptionType === 'constraint' && this.fieldConstraintsList.splice(this.formFieldOptionIndex, 1, this.fieldOptionForm)
        this.fieldOptionType === 'enum' && this.fieldEnumList.splice(this.formFieldOptionIndex, 1, this.fieldOptionForm)
      }
      this.fieldOptionModelVisible = false
      this.fieldOptionForm = {}
    },
    // 保存字段配置
    saveField() {
      const { id, type, label, defaultValue, datePattern } = this.formFieldForm
      const Field = window.bpmnInstances.moddle.create(`${this.prefix}:FormField`, { id, type, label })
      defaultValue && (Field.defaultValue = defaultValue)
      datePattern && (Field.datePattern = datePattern)
      // 构建属性
      if (this.fieldPropertiesList && this.fieldPropertiesList.length) {
        const fieldPropertyList = this.fieldPropertiesList.map(fp => {
          return window.bpmnInstances.moddle.create(`${this.prefix}:Property`, { id: fp.id, value: fp.value })
        })
        Field.properties = window.bpmnInstances.moddle.create(`${this.prefix}:Properties`, { values: fieldPropertyList })
      }
      // 构建校验规则
      if (this.fieldConstraintsList && this.fieldConstraintsList.length) {
        const fieldConstraintList = this.fieldConstraintsList.map(fc => {
          return window.bpmnInstances.moddle.create(`${this.prefix}:Constraint`, { name: fc.name, config: fc.config })
        })
        Field.validation = window.bpmnInstances.moddle.create(`${this.prefix}:Validation`, { constraints: fieldConstraintList })
      }
      // 构建枚举值
      if (this.fieldEnumList && this.fieldEnumList.length) {
        Field.values = this.fieldEnumList.map(fe => {
          return window.bpmnInstances.moddle.create(`${this.prefix}:Value`, { name: fe.name, id: fe.id })
        })
      }
      // 更新数组 与 表单配置实例
      if (this.formFieldIndex === -1) {
        this.fieldList.push(this.formFieldForm)
        this.formData.fields.push(Field)
      } else {
        this.fieldList.splice(this.formFieldIndex, 1, this.formFieldForm)
        this.formData.fields.splice(this.formFieldIndex, 1, Field)
      }
      this.updateElementExtensions()
      this.fieldModelVisible = false
    },
    // 移除某个 字段的 配置项
    removeFieldOptionItem(option, index, type) {
      if (type === 'property') {
        this.fieldPropertiesList.splice(index, 1)
        return
      }
      if (type === 'enum') {
        this.fieldEnumList.splice(index, 1)
        return
      }
      this.fieldConstraintsList.splice(index, 1)
    },
    // 移除 字段
    removeField(field, index) {
      this.fieldList.splice(index, 1)
      this.formData.fields.splice(index, 1)
      this.updateElementExtensions()
    },
    // 上传文件
    handleAvatarSuccess(res, file) {
      if (file.response.code === 200) {
        this.fileTable.push({ 'fileName': file.response.data.originalName, 'fileUrl': file.response.data.address })
        this.saveAttribute('systemFile', JSON.stringify(this.fileTable))
      }
    },
    // 移除文件
    removeAttributes(attr, index) {
      this.$confirm('确定移除当前文件么？', '提示', {
        confirmButtonText: '确 认',
        cancelButtonText: '取 消'
      })
        .then(() => {
          this.fileTable.splice(index, 1)
          this.saveAttribute('systemFile', JSON.stringify(this.fileTable))
        })
        .catch(() => console.info('操作取消'))
    },
    // 保存拓展字段
    saveAttribute(name, value) {
      // 判断当前属性是否存在
      this.elementPropertyList = JSON.parse(JSON.stringify(this.bpmnElementPropertyList ?? []))
      let index = -1
      for (let i = 0; i < this.elementPropertyList.length; i++) {
        let key = this.elementPropertyList[i].name
        if (name === 'systemFile' && key === 'systemFile') {
          index = i
        }
      }
      if (index !== -1) {
        window.bpmnInstances.modeling.updateModdleProperties(this.bpmnElement, this.bpmnElementPropertyList[index], {
          name,
          value
        })
      } else {
        // 新建属性字段
        const newPropertyObject = window.bpmnInstances.moddle.create(`${this.prefix}:Property`, { name, value })
        // 新建一个属性字段的保存列表
        const propertiesObject = window.bpmnInstances.moddle.create(`${this.prefix}:Properties`, {
          values: this.bpmnElementPropertyList.concat([newPropertyObject])
        })
        this.updateElementExtensions(propertiesObject)
      }
    },
    updateElementExtensions(properties) {
      const extensions = window.bpmnInstances.moddle.create('bpmn:ExtensionElements', {
        values: this.otherExtensionList.concat([properties])
      })
      window.bpmnInstances.modeling.updateProperties(this.bpmnElement, {
        extensionElements: extensions
      })
    },
    // 子页面回传参数
    checkData(data) {
      console.log('子页面回传参数', data)
      this.multipleSelection = data
    },
    // 确认
    deptSubmitForm() {
      this.institutionOpen = false
      this.fileTable = this.multipleSelection
      console.log('this.multipleSelection', this.fileTable)
      this.saveAttribute('systemFile', JSON.stringify(this.fileTable))
    },
    // 取消
    deptCancel() {
      this.institutionOpen = false
    },
    // 弹出显示
    isDialog() {
      this.institutionOpen = true
      this.$nextTick(() => {
        this.$refs.chooseInstitutionTable.init()
      })
    },
    // 获取详情
    getInfo(info) {
      this.institutionInfoOpen = true
      this.info = info
    },
  }
}
</script>
